package com.ccsoft.utils;

import com.ccsoft.constant.Constant;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;

/**
 * 2021年12月28日 09:40:14 chanchaw
 * 将 http file 写入本地文件
 */
public class FileWriter {
    private HttpURLConnection httpURLConnection = null;
    private String fullFilename = "";// 带有路径的文件名

    private InputStream inputStream = null;
    private BufferedInputStream bufferedInputStream = null;
    private RandomAccessFile randomAccessFile = null;
    private byte[] buffer = null;

    public FileWriter(HttpURLConnection httpURLConnection, String fullFilename) {
        this.httpURLConnection = httpURLConnection;
        this.fullFilename = fullFilename;

        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从网络文件读取数据到 buffer，并返回读取到的长度
    public int read() throws IOException {
        buffer = new byte[Constant.BYTE_SIZE];
        return bufferedInputStream.read(buffer);
    }

    public void write(int len) throws IOException {
        randomAccessFile.write(buffer,0,len);
    }

    private void init() throws IOException {
        inputStream = httpURLConnection.getInputStream();
        bufferedInputStream = new BufferedInputStream(inputStream);
        randomAccessFile = new RandomAccessFile(fullFilename,"rw");
    }
}
